import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sleep_manager/utils/toast_utils.dart';
import '../../globals.dart';
import '../home/home_page.dart';

/// 登录页面
class LoginPage extends StatefulWidget {

  const LoginPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage> {

  // 定义两个控制器来保存输入
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  // 记录上次点击的时间
  DateTime? _lastTapTime;

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvoked: (didPop) async {
        if (didPop) return; // 如果已经弹出，直接返回

        if(_lastTapTime == null || DateTime.now().difference(_lastTapTime!) > const Duration(seconds: 2)) {
          _lastTapTime = DateTime.now();
          showToast("再按一次退出应用");
        } else {
          SystemNavigator.pop();
        }
      },
      child: Scaffold(
        resizeToAvoidBottomInset: true,
        body: Container(
          width: double.infinity,
          height: double.infinity,
          color: Colors.white,
          child: Stack(
            children: [
              const Image(
                image: AssetImage("assets/images/login_bg.png"),
              ),
              SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      margin: const EdgeInsets.fromLTRB(32, 100, 0, 0),
                      child: const Image(
                        width: 180,
                        image: AssetImage("assets/images/login_logo.png"),
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(32, 43, 0, 0),
                      child: const Text(
                        "欢迎使用！",
                        style: TextStyle(
                            color: Color(0xFF343965),
                            fontSize: 30,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(32, 5, 0, 0),
                      child: const Text(
                        "穿戴式多导睡眠监测系统！",
                        style: TextStyle(
                            color: Color(0xFF343965),
                            fontSize: 20,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(32, 10, 0, 0),
                      child: const Text(
                        "智能检测 为健康护航",
                        style: TextStyle(
                            color: Color(0xFF343965),
                            fontSize: 14,
                            fontWeight: FontWeight.normal),
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(52, 30, 0, 0),
                      child: const Text(
                        "手机号",
                        style: TextStyle(
                          color: Color(0xFF343965),
                          fontSize: 12,
                        ),
                      ),
                    ),
                    buildTextField(
                        maxLength: 11,
                        controller: _phoneController,
                        keyboardType: TextInputType.phone
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(52, 10, 0, 0),
                      child: const Text(
                        "密码",
                        style: TextStyle(
                          color: Color(0xFF343965),
                          fontSize: 12,
                        ),
                      ),
                    ),
                    buildTextField(
                        maxLength: 6,
                        controller: _passwordController,
                        keyboardType: TextInputType.number
                    ),
                    GestureDetector(
                      onTap: validate,
                      child: Container(
                        margin: const EdgeInsets.fromLTRB(32, 62, 32, 0),
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(24),
                            gradient: const LinearGradient(
                                colors: [Color(0xFF80BFFF), Color(0xFF397AFB)],
                                begin: Alignment.centerLeft,
                                end: Alignment.centerRight)),
                        child: const Text(
                          "登录/注册",
                          style: TextStyle(color: Colors.white, fontSize: 18),
                        ),
                      ),
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  // 构建输入框
  Widget buildTextField({required int maxLength, required TextEditingController controller, required TextInputType keyboardType}) {
    return Container(
        margin: const EdgeInsets.fromLTRB(32, 5, 32, 0),
        padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 20),
        decoration: BoxDecoration(
            color: const Color(0xFFECF2FF),
            borderRadius: BorderRadius.circular(25)),
        child: TextField(
          maxLength: maxLength,
          controller: controller,
          keyboardType: keyboardType,
          decoration:
              const InputDecoration(border: InputBorder.none, counterText: ""),
        ));
  }

  // 校验函数
  void validate() {
    String phone = _phoneController.text;
    String password = _passwordController.text;

    String errorMessage = "";

    if (phone.length != 11) {
      errorMessage = "请输入正确的11位手机号";
    } else if (password != "123456") {
      errorMessage = "密码错误";
    }

    if (errorMessage.isNotEmpty) {
      showToast(errorMessage);
    } else {
      onLoginSuccess();
      Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => const HomePage())
      );
    }
  }

  // 登录成功
  void onLoginSuccess() {
    Globals.prefs?.setBool("isLoggedIn", true);
  }

}
